package com.eirikb.client.ui;

import com.eirikb.client.Client;
import com.eirikb.shared.events.MessageEvent;
import com.eirikb.shared.events.Event;
import com.eirikb.shared.events.JoinEvent;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.KeyboardListener;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

/**
 *
 * @author eirikb
 */
public class Chat extends SimplePanel {

    private TextArea chatArea;
    private TextBox chatBox;
    private ListBox nickList;
    private Client client;

    public Chat(Client client2) {
        this.client = client2;
        chatArea = new TextArea();
        chatBox = new TextBox();
        nickList = new ListBox();
        nickList.setVisibleItemCount(15);
        chatArea.setSize("640px", "480px");
        chatArea.setReadOnly(true);
        chatBox.setWidth("640px");
        chatArea.setVisibleLines(20);
        chatBox.addKeyboardListener(new KeyboardListener() {

            public void onKeyDown(Widget arg0, char arg1, int arg2) {
            }

            public void onKeyPress(Widget arg0, char arg1, int arg2) {
                if (arg1 == 13) {
                    addChat(client.getNick(), chatBox.getText());
                    Client.getService().sendMessage(client.getNick(), chatBox.getText(), null);
                    chatBox.setFocus(true);
                    chatBox.setText("");
                }
            }

            public void onKeyUp(Widget arg0, char arg1, int arg2) {
            }
        });

        addChat("Welcome to GWT-Chat");
        HorizontalPanel hPanel = new HorizontalPanel();
        VerticalPanel vPanel = new VerticalPanel();
        vPanel.add(chatArea);
        vPanel.add(chatBox);
        hPanel.add(vPanel);
        hPanel.add(nickList);
        add(hPanel);
    }
    
    public void addChat(String from, String msg) {
        addChat("<" + from + "> " + msg);
    }

    public void addChat(String msg) {
        chatArea.setReadOnly(false);
        chatArea.setFocus(true);
        chatArea.setText(chatArea.getText() + msg + '\n');
        chatArea.setCursorPos(chatArea.getText().length() - 1);
        chatArea.setFocus(false);
        chatArea.setReadOnly(true);
    }
    
    public void addNick(String nick) {
        nickList.addItem(nick);
    }

    public void removeNick(String nick) {
        for (int i = 0; i < nickList.getItemCount(); i++) {
            if (nickList.getItemText(i).equals(nick)) {
                nickList.removeItem(i);
                break;
            }
        }
    }
}
